import { Book, User, Comment } from '../models';
import { checkUserToken, formatTime2 } from '../utils/common';
import moment from 'moment';
import { ADMIN_USERNAME } from '../config';
import textCheck from '../utils/textCheck.js';

export default function (router) {
  /**
   * 前端接口
   * 添加评论
   */
  router.post('/api/front/comment/add', async ctx => {
    if (!ctx.state.user) return;
    const { userid } = ctx.state.user;
    let { bookid, content, father = null } = ctx.request.body;
    if (!bookid) {
      ctx.body = { ok: false, msg: '获取书籍信息失败' };
      return;
    }
    if (!content) {
      ctx.body = { ok: false, msg: '评论内容不能为空' };
      return;
    }
    if ((await textCheck(content)) !== '合规') {
      ctx.body = { ok: false, msg: '评论内容不合规' };
      return;
    }
    const thisComent = await Comment.create({
      userid: ctx.transId(userid),
      bookid: ctx.transId(bookid),
      father,
      content,
      like_num: 0,
      create_time: new Date()
    });
    // 查询用户信息
    const thisUser = await User.findById(userid);
    ctx.body = {
      ok: true,
      msg: '发表书评成功',
      data: {
        id: thisComent._id,
        username: thisUser.username,
        avatar: thisUser.avatar,
        userid: thisUser._id,
        father: thisComent.father,
        content: thisComent.content,
        is_like: false,
        like_num: 0,
        childs: [],
        create_time: formatTime2(thisComent.create_time)
      }
    };
  });

  /**
   * 前端接口
   * 评论点赞
   */
  router.get('/api/front/comment/like', async ctx => {
    if (!ctx.state.user) return;
    const { userid } = ctx.state.user;
    const { commentid, op } = ctx.request.query;
    if (op == 'add') {
      const updateResult = await Comment.updateOne({ _id: commentid }, { $addToSet: { like_persons: ctx.transId(userid) } });
      const currentComment = await Comment.findById(commentid);
      if (updateResult.ok == 1 && updateResult.nModified == 1) {
        ctx.body = {
          ok: true,
          msg: '点赞成功',
          current: currentComment.like_persons.length
        };
      } else {
        ctx.body = {
          ok: false,
          msg: '点赞失败',
          current: currentComment.like_persons.length
        };
      }
    } else if (op == 'remove') {
      const oldComment = await Comment.findById(commentid);
      const comments = oldComment.like_persons.filter(item => {
        return item.toString() != userid;
      });
      if (comments.length < oldComment.like_persons.length) {
        const updateResult = await Comment.updateOne({ _id: commentid }, { $set: { like_persons: comments } });
        const currentComment = await Comment.findById(commentid);
        if (updateResult.ok == 1 && updateResult.nModified == 1) {
          ctx.body = {
            ok: true,
            msg: '取消点赞成功',
            current: currentComment.like_persons.length
          };
        } else {
          ctx.body = {
            ok: false,
            msg: '取消点赞失败',
            current: currentComment.like_persons.length
          };
        }
      } else {
        ctx.body = { ok: false, msg: '取消点赞失败~' };
      }
    } else {
      ctx.body = { ok: false, msg: '点赞失败, 缺少op参数~' };
    }
  });

  /**
   * 前端接口
   * 获取评论列表（简单版）
   */
  router.get('/api/front/comments', async ctx => {
    const userid = ctx.state.user ? ctx.state.user.userid : '';
    const { bookid, page = 1 } = ctx.request.query;
    if (!bookid) {
      ctx.body = { ok: false, msg: '缺少bookid参数' };
      return false;
    }

    /**
     * 查询评论
     * 置顶 > 点赞人数 > 创建时间
     * 分页加载
     */
    const total = await Comment.countDocuments({ bookid: bookid, father: null });
    const comments = await Comment.find({ bookid: bookid, father: null })
      .populate({
        path: 'userid',
        options: {
          select: 'username avatar'
        }
      })
      .sort({ is_top: -1, like_persons: -1, create_time: -1 })
      .skip(3 * (parseInt(page) - 1))
      .limit(3);

    ctx.body = {
      ok: true,
      msg: '获取评论成功',
      hasMore: 3 * parseInt(page) < total,
      list: comments.map(item => {
        const user = item.userid || {};
        const isLike = item.like_persons.some(person => person.toString() === userid);
        return {
          id: item._id,
          userid: user._id,
          avatar: user.avatar,
          username: user.username,
          content: item.content,
          like_num: item.like_persons.length,
          is_like: isLike,
          create_time: item.create_time
        };
      })
    };
  });

  /**
   * 前端接口
   * 获取评论列表（评论详情）
   */
  router.get('/api/front/comment/detail', async ctx => {
    const userid = ctx.state.user ? ctx.state.user.userid : '';
    const { bookid } = ctx.request.query;
    const { page } = ctx.parsePageAndLimit(ctx.request.query);
    if (!bookid) {
      ctx.body = { ok: false, msg: '参数错误' };
      return;
    }

    const thisBook = await Book.findById(bookid, 'name');
    if (!thisBook) {
      ctx.body = { ok: false, msg: '数据不存在' };
      return;
    }

    const total = await Comment.countDocuments({ bookid });
    const comments = await Comment.find({ bookid })
      .populate({
        path: 'userid',
        select: 'avatar username'
      })
      .sort({ is_top: -1, like_persons: -1, create_time: -1 })
      .skip(10 * (parseInt(page) - 1))
      .limit(10);

    ctx.body = {
      ok: true,
      msg: '获取评论成功',
      hasMore: 10 * parseInt(page) < total,
      bookName: thisBook.name,
      list: comments.map(item => {
        const user = item.userid || {};
        const isLike = item.like_persons.some(person => person.toString() === userid);
        return {
          id: item._id,
          userid: user._id,
          avatar: user.avatar,
          username: user.username,
          content: item.content,
          like_num: item.like_persons.length,
          is_like: isLike,
          father: item.father,
          create_time: item.create_time
        };
      })
    };
  });

  /**
   * 前端接口
   * 获取回复自己的评论
   */
  router.get('/api/comment/my', async (ctx, next) => {
    let userid = await checkUserToken(ctx, next);
    if (userid) {
      // 获取到用户发布的所有评论
      const myComments = await Comment.find({ userid }, '_id like_persons')
        .populate({
          path: 'like_persons',
          select: 'username avatar'
        })
        .sort({ create_time: -1 });
      let likeComment = [];
      let replyComments = [];
      for (let i = 0; i < myComments.length; i++) {
        myComments[i].like_persons.forEach(likeItem => {
          likeComment.push({
            commentid: myComments[i]._id,
            avatar: likeItem.avatar,
            name: likeItem.username
          });
        });
        const reply = await Comment.find({ father: myComments[i]._id }, '_id bookid userid content create_time')
          .populate({
            path: 'userid',
            select: 'username avatar'
          })
          .sort({ create_time: -1 });
        reply.forEach(replyItem => {
          replyComments.push({
            commentid: replyItem._id,
            bookid: replyItem.bookid,
            avatar: replyItem.userid.avatar,
            name: replyItem.userid.username,
            content: replyItem.content,
            time: replyItem.create_time
          });
        });
      }
      ctx.body = {
        ok: true,
        msg: '获取我的消息成功',
        like: likeComment,
        reply: replyComments
      };
    }
  });

  /**
   * 后台接口
   * 获取评论列表
   */
  router.get('/api/admin/comment', async ctx => {
    let { page, limit, bookid } = ctx.request.query;
    // format page and limit
    if (page) {
      page = parseInt(page);
    } else {
      page = 1;
    }
    if (limit) {
      limit = parseInt(limit);
    } else {
      limit = 10;
    }
    let conf = {};
    if (bookid) {
      conf.bookid = bookid;
    }
    let total = await Comment.countDocuments(conf);
    let comments = await Comment.find(conf)
      .populate({
        path: 'bookid',
        model: 'Book',
        select: { name: 1 }
      })
      .populate({
        path: 'userid',
        model: 'User',
        select: { username: 1 }
      })
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ create_time: -1 });
    ctx.body = { ok: true, msg: '获取评论成功', total, list: comments };
  });

  /**
   * 后台接口
   * 管理员回复评论
   */
  router.post('/api/admin/comment/reply', async ctx => {
    let { bookid, commentid, content, send_message } = ctx.request.body;
    if (!bookid) {
      ctx.body = { ok: false, msg: '参数错误，缺乏bookid参数' };
      return false;
    }
    if (!commentid) {
      ctx.body = { ok: false, msg: '参数错误，缺乏commentid参数' };
      return false;
    }
    if (!content) {
      ctx.body = { ok: false, msg: '参数错误，缺乏content参数' };
      return false;
    }
    send_message = !!send_message;
    // 创建一条系统回复评论
    // 当前书籍
    let curBook = await Book.findById(bookid, 'name');
    if (!curBook) {
      ctx.body = { ok: false, msg: '评论未找到' };
      return false;
    }
    // 当前评论
    let curComment = await Comment.findById(commentid, 'content userid');
    if (!curComment) {
      ctx.body = { ok: false, msg: '评论未找到' };
      return false;
    }
    // 查找管理员
    let adminUser = await User.findOne({ username: ADMIN_USERNAME });
    if (!adminUser) {
      ctx.body = { ok: false, msg: '系统管理员未找到' };
      return false;
    }
    let newComment = await Comment.create({
      userid: ctx.transId(adminUser._id),
      bookid: ctx.transId(bookid),
      father: commentid ? ctx.transId(commentid) : null,
      content: content,
      like_num: 0,
      create_time: new Date()
    });
    // 发送模板消息
    if (send_message) {
      User.sendMessage(
        curComment.userid.toString(),
        'comment',
        {
          keyword1: { value: `《${curComment.content}》` },
          keyword2: { value: curBook.name },
          keyword3: { value: '系统管理员' },
          keyword4: { value: moment(newComment.create_time).format('YYYY年MM月DD日 HH:mm:ss') },
          keyword5: { value: '点击查看详情' }
        },
        { bookid: bookid }
      );
    }
    ctx.body = { ok: true, msg: '回复成功', data: newComment };
  });

  /**
   * 后台接口
   * 评论删除
   */
  router.delete('/api/admin/comment', async ctx => {
    const commentid = ctx.request.body.commentid;
    const bookid = ctx.request.body.bookid;
    let curComment = await Comment.findById(commentid);
    if (!curComment) {
      ctx.body = { ok: false, msg: '评论未找到' };
      return false;
    }
    let curBook = await Book.findById(bookid, 'name');
    if (!curBook) {
      ctx.body = { ok: false, msg: '评论未找到' };
      return false;
    }
    // 找出当前评论以及当前评论的子评论
    let comments = [];
    comments.push(commentid);
    let findChildAndSon = async function (commentId) {
      let childComments = await Comment.find({ bookid: bookid, father: commentId });
      let childCommentsToSave = [];
      childComments.forEach(function (childItem) {
        childCommentsToSave.push(childItem._id.toString());
      });
      comments = comments.concat(childCommentsToSave);
      // when this comment has child
      if (childComments.length > 0) {
        for (let k = 0; k < childComments.length; k++) {
          await findChildAndSon(childComments[k]._id);
        }
      }
    };
    await findChildAndSon(commentid);
    let deleTeResult = await Comment.deleteOne({ _id: { $in: comments } });
    if (deleTeResult.ok === 1) {
      ctx.body = { ok: true, msg: '删除评论成功' };
    } else {
      ctx.body = { ok: false, msg: '删除评论失败', data: deleTeResult.result };
    }
  });
}
